package cn.gson.boot.controller;

import cn.gson.boot.model.pojos.*;
import cn.gson.boot.model.service.EmpService;
import cn.gson.boot.model.service.HeTongService;
import cn.gson.boot.model.service.JiaoFuJiHuaService;
import cn.gson.boot.model.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/htdd")
public class HeTongDingDanController {
    @Autowired
    HeTongService heTongService;
    @Autowired
    EmpService empService;


    @RequestMapping("/ckKeHu")
    @ResponseBody
    //查询客户的姓名集合
    public List<String> selectKehu(){
        List<Kehu> kehus = heTongService.selectKehu();
        List<String> khNames = new ArrayList<>();//客户姓名集合
        for (int i=0;i<kehus.size();i++){
            System.out.println(kehus.get(i).getkName());
            khNames.add(kehus.get(i).getkName());
        }
        return khNames;
    }

    @RequestMapping("/ckBaoJiaDan")
    @ResponseBody
    public List<Quotation> selectBaoJiaDanByKeHU(String khName){
        System.err.println("客户没："+khName);
        Integer khid = heTongService.selectKhIdBykhName(khName);//根据客户名查客户id
        return heTongService.selectBaoJiaDidanByKeHU(khid);//查询客户所对应的报价单
    }

    @RequestMapping("/ckKhId")
    @ResponseBody
    //根据客户名字找客户id
    public Kehu selectKhidByKhName(String khName2){
        System.err.println("客户没2："+khName2);
        return heTongService.selectKhIdBykhNameDuixiang(khName2);//根据客户名查客户id
    }

    @RequestMapping("/ckEmpId")
    @ResponseBody
    //根据员工名字找员工
    public User selectKhidByEmpName(String empName){
        System.err.println("员工2："+empName);
        return heTongService.selectEmpIdByEmpName(empName);
    }


    @RequestMapping("/ckUser")
    @ResponseBody
    //查询员工的姓名集合
    public List<String> selectUser(){
        List<User> users = heTongService.selectUser();
        List<String> userNames = new ArrayList<>();//员工姓名集合
        for (int i=0;i<users.size();i++){
            System.out.println(users.get(i).getEmpName());
            userNames.add(users.get(i).getEmpName());
        }
        return userNames;
    }

    @RequestMapping("/ckBaoJiaMingXi")
    @ResponseBody
    //根据报价单id查询报价明细
    public List<Quotationdetails> selectBaoJiaMingXi(Integer baojiaId){
        System.err.println("baojai1dan1:"+baojiaId);
      //  System.err.println(heTongService.selectBaoJiaMingXi(baojiaId).get(0).getProduct()+"======="+heTongService.selectBaoJiaMingXi(baojiaId).get(0).getQuotationdMoney());
        return heTongService.selectBaoJiaMingXi(baojiaId);
    }

    @RequestMapping("/addHeTong")
    @ResponseBody
    //新建合同
    public void addHeTongOk(@RequestBody Hetong hetong){
        System.err.println("修改合同：合同id："+hetong.getHtId());
        System.err.println("baojai1dan1:"+hetong.getHtHao());
        System.err.println("baojai1dan222:"+hetong.baoJiaMingXiList.get(0).getQuotationdMoney());

        System.err.println("keuhIDID:"+hetong.getkH().getkId());
        System.err.println("empIDID:"+hetong.getEmp().getEmpId());
        heTongService.addHetongAndXiangQing(hetong);
    }


    //查看所有合同
    @RequestMapping("/ckHeTong")
    @ResponseBody
    public Map<String,Object> aA(String htHao, String khName, String time, String htSh,
                                 Integer pageNumm, Integer pageSizee, HttpSession session) {
        Page<Object> objects = PageHelper.startPage(pageNumm, pageSizee);

        String time3 = null;
        if(time != null && time != "" && !time.equals("")){
            StringBuffer time1 = new StringBuffer(time.substring(0,10));
            System.err.println("tim1:"+time1);
            //日期这里会有问题，如果是月底的话就会出错，要判断一下是大月还是小月，是否是闰年
            int ti = Integer.parseInt(time1.substring(8))+1;
            System.err.println("ti:"+ti);
            String tistr = toString().valueOf(ti);
            if(toString().valueOf(ti).length() == 1){
                tistr = 0 + toString().valueOf(ti);
            }
            StringBuffer time2 = new StringBuffer(time1.replace(8,time1.length(), tistr));
            System.err.println("tim2:"+time2);
            time3 = time2.toString();
        }
        if(htSh.equals("全部数据")){
            htSh = null;
        }
        User us = (User)session.getAttribute("user");
        List<UserLogin> users = (List<UserLogin>)session.getAttribute("users");
        List<Role> roles = users.get(0).getRoleListss();
        List<String> jueNameList = new ArrayList<>();
        for(int i=0;i<roles.size();i++){
            System.out.println("角色名称："+roles.get(i).getJueName());
            jueNameList.add(roles.get(i).getJueName());
        }
        String empName = null;
        if(jueNameList.indexOf("boss")>-1 ||jueNameList.indexOf("销售经理")>-1  ){
            empName = null;
        }else{
            empName = us.getEmpName();
        }

        List<Hetong> list = heTongService.selectAllHeTong(htHao,khName,time3,htSh,empName);

        Map<String,Object> map = new HashMap();
        map.put("total", objects.getTotal());
        map.put("list", list);
        return map;
    }

    //查看合同详情根据合同id
    @RequestMapping("/ckHeTongXiangQing")
    @ResponseBody
    public List<Hetongxiangqing> ckHeTongXiangQing(Integer htid){

        return heTongService.ckHeTongXiangQing(htid);
    }


    //移除合同
    @RequestMapping("/yichuHeTong")
    @ResponseBody
    public String yichuHeTong(Integer htid){
        return heTongService.yichuHeTong(htid);
    }


    //订单==========================================================================

    //新建订单，查看所有的合同状态是执行中的合同
    @RequestMapping("/ddCkHt")
    @ResponseBody
    public List<Hetong> ddCkHt(){
        /*ckHeTongXiangQing
        selectDDDingDanXaingQing
        先查到所有的合同ddCkHt，再根据ddCkHt中的合同id查到ckHeTongXiangQing（合同详情）和
        selectDDDingDanXaingQing（订单详情），*/
       /* List<Hetong> ht = heTongService.ddCkHt();//合同
        List<Hetongxiangqing> htxq = null;//合同详情
        List<Dingdanxiangqing> ddxq = null;//订单详情
        for (int i=0;i<ht.size();i++){
            htxq = heTongService.ckHeTongXiangQing(ht.get(i).getHtId());
            ddxq = heTongService.selectDDDingDanXaingQing(ht.get(i).getHtId());
            for(int j=0;j<ddxq.size();j++){
                //再判断合同详情中的产品和数量是不是已经在订单中完成了
                if(ddxq.get(j).getProduct().getProductId() ==
                htxq.get(j).getProduct().getProductId() &&
                ddxq.get(j).getDdcpNum() == htxq.get(j).getHtcpMun())
               //完成就再ddCkHt中移除此合同，再返回
                ht.remove(i);
                break;
            }
        }*/

       //合同没失效(合同结束时间  晚于 当前的时间)
        List<Hetong> ht = heTongService.ddCkHt();
        Timestamp ts = new Timestamp(new Date().getTime());
        List<Hetong> abk = new ArrayList<>();

        for(int i=0;i<ht.size();i++){
            if(!ht.get(i).getHtJieshutime().before(ts)){
                abk.add(ht.get(i));
            }
        }


        return abk;
    }

    //根据合同id查合同详情(mybatis查询)
    @RequestMapping("/ddCkHtxq")
    @ResponseBody
    public List<Hetongxiangqing> selectDDHeTongXaingQing(Integer htId){
        return heTongService.selectDDHeTongXaingQing(htId);
    }
    //根据合同id查看订单详情<四个表：合同，订单，订单详情，产品>(mybatis查询)
    @RequestMapping("/ddCkddxq")
    @ResponseBody
    public List<Dingdanxiangqing> selectDDDingDanXaingQing(Integer htId){
        System.err.println("htidAVCDSED:"+htId);
        return heTongService.selectDDDingDanXaingQing(htId);
    }



    //新建订单
    @RequestMapping("/addDinDan")
    @ResponseBody
    public void addDinDan(@RequestBody Dingdan dingdan){
        System.out.println("新建订单：：：："+dingdan);
        heTongService.addDinDan(dingdan);
    }

    //查看所有订单
    @RequestMapping("/ckDingDan")
    @ResponseBody
    public Map<String,Object> bB(String ddHao,String khName,String time, String ddZt,
                                 Integer pageNumm, Integer pageSizee,HttpSession session){
        Page<Object> objects = PageHelper.startPage(pageNumm, pageSizee);

        String time3 = null;
        if(time != null && time != "" && !time.equals("")){
            StringBuffer time1 = new StringBuffer(time.substring(0,10));
            System.err.println("tim1:"+time1);
            //日期这里会有问题，如果是月底的话就会出错，要判断一下是大月还是小月，是否是闰年
            int ti = Integer.parseInt(time1.substring(8))+1;
            System.err.println("ti:"+ti);
            String tistr = toString().valueOf(ti);
            if(toString().valueOf(ti).length() == 1){
                tistr = 0 + toString().valueOf(ti);
            }
            StringBuffer time2 = new StringBuffer(time1.replace(8,time1.length(), tistr));
            System.err.println("tim2:"+time2);
            time3 = time2.toString();
        }

        User us = (User)session.getAttribute("user");
        List<UserLogin> users = (List<UserLogin>)session.getAttribute("users");
        List<Role> roles = users.get(0).getRoleListss();
        List<String> jueNameList = new ArrayList<>();
        for(int i=0;i<roles.size();i++){
            jueNameList.add(roles.get(i).getJueName());
        }
        String empName = null;
        if(jueNameList.indexOf("boss")>-1 ||jueNameList.indexOf("销售经理")>-1  ){
            empName = null;
        }else{
            empName = us.getEmpName();
        }

        if(ddZt.equals("全部数据")){
            ddZt = null;
        }
        List<Dingdan> list = heTongService.selectAllDingDan2(ddHao,khName,time3,ddZt,empName);
        Map<String,Object> map = new HashMap();
        map.put("total", objects.getTotal());
        map.put("list", list);
        return map;
    }


    //查看订单id查看订单详情
    @RequestMapping("/ckDingDanXiangQing")
    @ResponseBody
    public List<Dingdanxiangqing> ckDingDanXiangQing(Integer ddid){

        return heTongService.ckDingDanXiangQing(ddid);
    }


    //移除订单
    @RequestMapping("/yichuDingDan")
    @ResponseBody
    public String yichuDingDan(Integer ddid){

        return heTongService.yichuDingDan(ddid);
    }

    //根据合同id查看合同
    @RequestMapping("/selectHeTongByHtId")
    @ResponseBody
    public List<Hetong> selectHeTongByHtId(Integer htId){
        return heTongService.selectHeTongByHtId(htId);
    }


    /*重复购买*/
    //查看所有订单
    @RequestMapping("/aa")
    @ResponseBody
    public List<Dingdan> bB2() {
        return heTongService.selectAllDingDan(new Dingdan(null));
    }
//=================交付计划======================
    @Autowired
    JiaoFuJiHuaService jiaoFuJiHuaService;
    //交付计划（查看所有订单）[如果订单已经再交付计划中就要移除，
    // 并且订单详情里面产品的数量和交付计划中产品的数量相同]
    @RequestMapping("/jfjhSelectAllDingDan")
    @ResponseBody
    public List<Dingdan> jfjhSelectAllDingDan(){
        List<Dingdan> dd = heTongService.jfjhSelectAllDingDan();
        //List<Jiaofujihua> jj = jiaoFuJiHuaService.selectAllJiaoFuJiHua("","","","");
       // System.err.println("ASD:"+jj.get(0).getJjBeizhu());
        List<Dingdanxiangqing> dx = null;
        List<Dingdan> dd2 = new ArrayList<>();
        for(int i=0;i<dd.size();i++){
            dx = selectDingDanByDdId(dd.get(i).getDdId());
            if(dx.size()==0){
                dd2.add(dd.get(i));
            }
        }
        dd.removeAll(dd2);
      /*  System.err.println("size:"+dd.size());
        List<Dingdanxiangqing> dx = null;
        List<Jiaofujihuaxiangqing> jx = null;

        int size = 0;
        int  size0 = 0;
        for(int i=0;i<jj.size();i++){
           for(int j=0;j<dd.size();j++){
               size0 = 0;
               size = 0;
               System.out.println("jjjjaajasjaj:"+j);
               //如果订单已经再交付计划中
               if(jj.get(i).getDingdanByDdId().getDdId() == dd.get(j).getDdId()){
                  dx = heTongService.selectDingDanByDdId(dd.get(j).getDdId());//根据订单id查看订单详情
                  jx = jiaoFuJiHuaService.selectJJXQbyDdId(dd.get(j).getDdId());//根据订单id查询交付计划详情
                   //并且订单详情里面产品的数量和交付计划中产品的数量相同
                  for(int m=0;m<dx.size();m++){
                      for(int n=0;n<jx.size();n++){
                          if(dx.get(m).getProductt().getProducttId() == jx.get(n).getProductt().getProducttId()){
                              //&& dx.get(m).getDdcpNum() == jx.get(n).getJfjhxqNum()
                              //就要移除
                             *//* System.err.println("j:"+j);
                              System.err.println("m:"+dx.get(m).getProductt().getProductName());
                              System.err.println("n:"+jx.get(n).getProduct().getProductName());
                              System.err.println("m2:"+dx.get(m).getDdcpNum());
                              System.err.println("n2:"+jx.get(n).getJfjhxqNum());*//*
                                size += jx.get(n).getJfjhxqNum();
                          }
                      }
                      size0 += dx.get(m).getDdcpNum();
                  }
               }
               System.err.println("size0订单:"+size0);
               System.err.println("size交付计划:"+size);
           }*/
       // }
        return dd;
    }

    //根据选择的订单获取订单详情
    @RequestMapping("/selectDingDanByDdId")
    @ResponseBody
    public List<Dingdanxiangqing> selectDingDanByDdId(Integer ddid){
        //订单详情里面产品的数量和交付计划中产品的数量相同
        List<Dingdanxiangqing> dx = heTongService.selectDingDanByDdId(ddid);//根据订单id查看订单详情
        List<Jiaofujihuaxiangqing> jx  = jiaoFuJiHuaService.selectJJXQbyDdId(ddid);//根据订单id查询交付计划详情
        for(int i=0;i<dx.size();i++){
            for(int j=0;j<jx.size();j++){
                //相同则移除
                if(dx.get(i).getProductt().getProduct().getProductId() == jx.get(j).getProductt().getProduct().getProductId()){
                    //就要移除
                    if(dx.get(i).getDdcpNum() == jx.get(j).getJfjhxqNum()){
                        dx.remove(i);
                    }else if(dx.get(i).getDdcpNum() != jx.get(j).getJfjhxqNum()){//不同则修改数量
                        dx.get(i).setDdcpNum(dx.get(i).getDdcpNum() - jx.get(j).getJfjhxqNum());
                        dx.get(i).setDdxqXiaoji(
                                new BigDecimal(
                                        (dx.get(i).getDdcpNum())
                                                *Double.parseDouble(dx.get(i).getDdcpPrice().toString())
                                )
                        );
                        System.err.println("数量："+dx.get(i).getDdcpNum());
                        System.err.println("价格："+dx.get(i).getDdcpPrice());
                        System.err.println("小计："+dx.get(i).getDdxqXiaoji());
                    }
                }
            }
        }
        return dx;
    }

    //根据订单id获取订单
    @RequestMapping("/selectDDByDDid")
    @ResponseBody
    public List<Dingdan> selectDDByDDid(Integer ddId){
        return heTongService.selectDDByDDid(ddId);
    }


    @RequestMapping("/selectheBaoHangDeDingDan")
    @ResponseBody
    //根据合同查到此合同包含的订单
    public List<Dingdan> selectheBaoHangDeDingDan(Integer htId){
        return heTongService.selectheBaoHangDeDingDan(htId);
    }

    /*重复购买订单==========================================*/
    @RequestMapping("/addCFGMdingdan")
    @ResponseBody
    //根据合同查到此合同包含的订单
    public void addCFGMdingdan(@RequestBody CFGMDingdan cfgmDingdan){
        heTongService.addCFGMdingdan(cfgmDingdan);
    }

    //查看所有重复购买订单
    @RequestMapping("/ckcfgmDingDan")
    @ResponseBody
    public Map<String,Object> ckcfgmDingDan(String ddHao,String khName,String time, Integer pageNumm, Integer pageSizee){
        Page<Object> objects = PageHelper.startPage(pageNumm, pageSizee);

        String time3 = null;
        if(time != null && time != "" && !time.equals("")){
            StringBuffer time1 = new StringBuffer(time.substring(0,10));
            System.err.println("tim1:"+time1);
            int ti = Integer.parseInt(time1.substring(8))+1;
            System.err.println("ti:"+ti);
            String tistr = toString().valueOf(ti);
            if(toString().valueOf(ti).length() == 1){
                tistr = 0 + toString().valueOf(ti);
            }
            StringBuffer time2 = new StringBuffer(time1.replace(8,time1.length(), tistr));
            System.err.println("tim2:"+time2);
            time3 = time2.toString();
        }
        List<Dingdan> list = heTongService.ckcfgmDingDan(ddHao,khName,time3);

        Map<String,Object> map = new HashMap();
        map.put("total", objects.getTotal());
        map.put("list", list);
        return map;
    }


    /*统计图*/

    //合同thtj
    @RequestMapping("/hetongtj")
    @ResponseBody
    public Map<String,Object> hetongtj(String lx){
        Map<String,Object> map = new HashMap<>();
        if(lx.equals("合同状态")){
            map = heTongService.htZhuanTai();
        }else if(lx.equals("审核状态")){
            map = heTongService.htSh();
        }else if(lx.equals("用户")){
            map = heTongService.htYh();
        }else if(lx.equals("报价单")){
            map = heTongService.htBjd();
        }else if(lx.equals("所有者")){
            map = heTongService.htSyz();
        }
        return map;
    }

    //根据订单id找到此订单的所有回款计划
    @RequestMapping("/selectHuiKuanByddId")
    @ResponseBody
    public List<Huikuan> selectHuiKuanByddId(Integer ddId){
        return heTongService.selectHuiKuanByddId(ddId);
    }



    //根据合同id找到合同
    @RequestMapping("/selectHeTongByhtIdSh")
    @ResponseBody
    public Hetong selectHeTongByhtIdSh(Integer htId){
        return heTongService.selectHeTongByhtIdSh(htId);
    }

    //根据订单id找到订单
    @RequestMapping("/selectDingDanByddIdSh")
    @ResponseBody
    public Dingdan selectDingDanByddIdSh(Integer ddId){
        return heTongService.selectDingDanByddIdSh(ddId);
    }


    //根据员工姓名来查询员工
    @RequestMapping("/selectEmpByEmpName")
    @ResponseBody
    public User selectEmpByEmpName(String empName){
        return empService.selectEmpByEmpName(empName);
    }
}
